<?php

namespace App\Services\Wxpay;

class WxpayNotify extends \WxPayNotifyReply
{
    final public function Handle($callback, $needSign = true)
    {
        $msg = "OK";
        //当返回false的时候，表示notify中调用NotifyCallBack回调失败获取签名校验失败，此时直接回复失败
        $result = self::notify($callback, $msg);
        if($result == false){
            $this->SetReturn_code("FAIL");
            $this->SetReturn_msg($msg);
            $this->ReplyNotify(false);
            return;
        } else {
            //该分支在成功回调到NotifyCallBack方法，处理完成之后流程
            $this->SetReturn_code("SUCCESS");
            $this->SetReturn_msg("OK");
        }
        $this->ReplyNotify($needSign);
    }

    public static function notify($callback, &$msg)
    {
        //获取通知的数据
        $xml = file_get_contents('php://input');
        //如果返回成功则验证签名
        try {
            $WxPayResults = new \WxPayResults;
            $WxPayResults->FromXml($xml);
            $result = $WxPayResults->GetValues();
            if ( $result['trade_type'] == 'APP' ){
                require_once 'libs/WxPay.Config.App.php';
            }else{
                require_once 'libs/WxPay.Config.Native.php';
            }
            $WxPayResults->CheckSign();
        } catch (\WxPayException $e){
            $msg = $e->errorMessage();
            return false;
        }
        
        return call_user_func($callback, $result);
    }

    public function replyFailNotify($msg)
    {
        $this->SetReturn_code("FAIL");
        $this->SetReturn_msg($msg);
        $this->ReplyNotify(false);
    }
    
    /**
     * 
     * 回复通知
     * @param bool $needSign 是否需要签名输出
     */
    final private function ReplyNotify($needSign = true)
    {
        //如果需要签名
        if($needSign == true && 
            $this->GetReturn_code() == "SUCCESS")
        {
            $this->SetSign();
        }
        \WxpayApi::replyNotify($this->ToXml());
    }

}